<template>
  <div class="container">
    <div class="export-header">
      <el-button  icon="el-icon-edit" type="primary" size='medium' @click="addBtn('')">添加</el-button>
      <el-button  icon="el-icon-edit" type="primary" size='medium' @click="addBtn('more')">批量添加</el-button>
      <el-button type="primary" size='medium' @click="changeState('y')">批量激活</el-button>
      <el-button type="primary" size='medium' @click="changeState('n')">批量失效</el-button>
      <el-button type="primary" size='medium' @click="dialogVisible1 = true">批量延期</el-button>
      <el-button type="primary" size='medium' @click="exportClick">导出</el-button>
    </div>
    <div class="input_modal">
      <div class="input-item">
        <span>卡号：</span>
        <el-input v-model="param.couponCode" placeholder="请输入内容" class="proName" @keyup.enter.native="search"></el-input>
      </div>
      <div class="input-item">
        <span>福利卡券名称：</span>
        <el-input v-model="param.couponName" placeholder="请输入内容" class="proName" @keyup.enter.native="search"></el-input>
      </div>
       <div class="input-item">
        <span>类型：</span>
        <el-select v-model='param.type' placeholder='-请选择-' @change="getList" style="height: 30px;  line-height: 30px;width:200px;">
          <el-option label="全部" value="" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
          <el-option label="实体卡" value="real" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
          <el-option label="虚拟卡" value="virtual" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
        </el-select>
      </div>
      <div class="input-item">
        <span>有效期：</span>
         <el-date-picker
            v-model="dateArr"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
        </el-date-picker>
      </div>
      <div class="input-item">
        <span>激活情况：</span>
        <el-select v-model='param.status' placeholder='-请选择-' @change="getList" style="height: 30px;  line-height: 30px;width:200px;">
          <el-option label="全部" value="" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
          <el-option label="已激活" value="y" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
          <el-option label="失效" value="n" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
        </el-select>
      </div>
      <div class="input-item">
        <span>充值情况：</span>
        <el-select v-model='param.isRecharge' placeholder='-请选择-' @change="getList" style="height: 30px;  line-height: 30px;width:200px;">
          <el-option label="全部" value="" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
          <el-option label="已充值" value="y" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
          <el-option label="待充值" value="n" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
        </el-select>
      </div>
      <div class="input-item">
        <span>充值手机号：</span>
        <el-input v-model="param.mobile" placeholder="请输入内容" class="proName" @keyup.enter.native="search"></el-input>
        <el-button icon="el-icon-search" type="primary" size="medium" @click="getList">查询</el-button>
      </div>
    </div>
    <div class="table_con">
      <el-table :row-key="getRowKeys" @selection-change="handleSelectionChange" v-loading="loading" :data="tableData" :border='true'>
          <el-table-column
          fixed="left"
          type="selection"
          min-width='100'
          :reserve-selection="true"
          align="center"
        ></el-table-column> 
        <el-table-column :formatter="formatter" prop="couponCode" label="卡号"></el-table-column>
        <el-table-column :formatter="formatter" prop="couponPsw" label="卡密"></el-table-column>
        <el-table-column :formatter="formatter" prop="type" label="类型">
          <template slot-scope="scope">
                {{returnName(scope.row.type)}}
              </template>
            </el-table-column>
        <el-table-column  prop="restPrice" label="余额"></el-table-column>
        <el-table-column :formatter="formatter" prop="validTime" label="有效期"></el-table-column>
        <el-table-column :formatter="formatter" prop="status" label="激活情况">
          <template slot-scope="scope">
            {{scope.row.status == 'y'?'已激活':'失效'}}
          </template>
        </el-table-column>
        </el-table-column>
        <el-table-column :formatter="formatter" prop="isRecharge" label="充值情况">
          <template slot-scope="scope">
            {{scope.row.isRecharge == 'y'?'已充值':'待充值'}}
          </template>
        </el-table-column>
        <el-table-column :formatter="formatter" prop="mobile" label="充值手机号"></el-table-column>
        <el-table-column width="250" prop="" label="操作">
          <template slot-scope="scope">
              <el-button @click="linkTo('couponCheck',scope.row.id)" type="primary" size="mini">查看</el-button>
            <el-button   @click="editBtn(scope.row.id)" type="primary" size="mini">编辑</el-button>
            <el-button  @click="openBtn(scope.row)" type="primary" size="mini">{{scope.row.status == 'y'?'失效':'激活'}}</el-button>
            <el-button  @click="changeMobile(scope.row)" type="primary" size="mini">充值</el-button>
            <el-button  type="danger" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="param.pageIndex" :page-size="param.pageSize" :page-sizes='[10,20,30,100]' layout="total, sizes, prev, pager, next, jumper" :total="pageCount">
      </el-pagination>
    </div>
    <el-dialog title="充值" :visible.sync="dialogVisible" width="30%">
      <div class="tag-head">
        <el-form :model="user" :rules="rules" ref="user" label-width="120px" class="">
          <div style="text-align:center;margin-bottom:20px">请填写要充值的金额</div>
          <el-form-item label="充值金额" prop="phoneNum">
            <el-input v-model="price" placeholder="请输入充值金额"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handSave('user')" type="primary">确 定</el-button>
        <el-button style="margin-right:30%" type="primary" @click="dialogVisible = false">返 回</el-button>
      </span>
    </el-dialog>
    <el-dialog title="延期" :visible.sync="dialogVisible1" width="30%">
      <div class="tag-head">
        <el-form :model="user1" :rules="rules1" ref="user1" label-width="120px" class="">
          <el-form-item label="有效期延长至" prop="phoneNum">
            <el-date-picker
                v-model="user1.validTime"
                type="date"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handSave1('user1')" type="primary">确 定</el-button>
        <el-button style="margin-right:30%" type="primary" @click="dialogVisible1 = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
let CONSTANT = require("../../constant/constant.js");
let common = require("../../common.js");
export default {
  data() {
    return {
      tableData: [],
      dateArr:[],
      dialogVisible:false,
      dialogVisible1:false,
      pageCount: null,
      pageIndex: 1,
      pageSize: 10,
      loading: true,
      user:{
          phoneNum:''
      },
      user1:{
        validTime:''
      },
      param:{
        pageIndex:1,
        pageSize:10,
        couponCode:'',
        couponName:'',
        type:"",
        status:'',
        isRecharge:'',
        mobile:'',
        beginDate:'',
        endDate:''
      },
      couponCode:'',
      couponName:'',
      isRecharge:'',
      mobile:'',
      phoneNum:'',
      status:'',
      type:'',
      price:'',
      rules: {
        // phoneNum: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      rules1: {
        validTime: [{ required: true, message: "请选择有效期", trigger: "blur" }],
      },
      typeArr:[
        {
            name:'实体卡',
            value:'real'
        },
         {
            name:'虚拟卡',
            value:'virtual'
        }
      ],
      couponObj:{},
      selectVal:[],
      ids:[],
      nowDate:''
    };
  },
  mounted() {
    if(this.$router.currentRoute.query.pageIndex){
      this.param = JSON.parse(this.$router.currentRoute.query.pageIndex)
    }
    this.getList();
    this.getNowFormatDate()
  },
  methods: {
   getNowFormatDate() {
        var date = new Date();
        var seperator1 = "/";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        this.nowDate = year + seperator1 + month + seperator1 + strDate;
    },
    returnBtnState(dateValid){
      let state = true;
      
      dateValid = dateValid.replace(/-/g,  "/").split(' ')[0]
      dateValid = new Date(dateValid).getTime()
      let nowDateTimes = new Date(this.nowDate).getTime()
      if(dateValid<nowDateTimes){
        state = false
      }
      return state
    },
    getRowKeys(row) {
      return row.id;
    },
    exportClick(){
      
      this.dateArr = this.dateArr?this.dateArr:[]
        if(this.dateArr.length){
            this.param.beginDate = this.dateArr[0]
            this.param.endDate = this.dateArr[1]
        }else{
          this.param.beginDate = ''
          this.param.endDate = ''
        }
      let sessionId = sessionStorage.getItem('sessionId');
      let url = `${CONSTANT.URL.LIST.couponExport}?sessionId=${sessionId}`;
       var data = {
          couponCode:this.param.couponCode,
          couponName:this.param.couponName,
          isRecharge:this.param.isRecharge,
          mobile:this.param.mobile,
          status:this.param.status,
          type:this.param.type,
          beginDate:this.param.beginDate,
          endDate:this.param.endDate,
          isAll:this.ids.length?'n':'y',
          ids:this.ids
       }
       for (let item in data) {
        if (!data[item] && data[item] !== false) {
          delete data[item]
        }
      }
       common.post1(url, JSON.stringify(data), res => {
         var blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          console.log(blob,'blob')
          blob = URL.createObjectURL(blob)
          var fileName = "福利卡.xlsx"
          let link = document.createElement('a')
          link.href = blob
          link.download = fileName
          link.click()
          link.remove()
      });
    },
    handleSelectionChange(val){
      this.ids = []
      this.selectVal = []
      this.selectVal = val
      this.selectVal.map(item=>{
        this.ids.push(item.id)
      })
    },
    changeState(state){
      if(!this.selectVal.length) return
      // let stateBtn = false
      // this.selectVal.forEach(item=>{
      //   if(item.isRecharge == 'y'){
      //     stateBtn = true
      //   }
      // })
      // if(stateBtn){
      //   this.$message({
      //     type: "warning",
      //     message: '已充值账户不能执行该操作'
      //   });
      //   return  
      // }
      this.selectVal.forEach(item=>{
        item.status = state
      })
       let url = CONSTANT.URL.LIST.changeStatus;
          common.requestAjax(url, JSON.stringify(this.selectVal), null, res => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "操作成功！"
              });
              this.getList();
            } else {
              this.$message({
                type: "warning",
                message: res.msg
              });
            }
          });
    },
    openBtn(obj){
       this.$confirm(`确定${ obj.status == 'y'?'失效':'激活'}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          obj.status = obj.status == 'y'?'n':'y'
          let url = CONSTANT.URL.LIST.saveEsCoupon;
          common.requestAjax(url, JSON.stringify(obj), null, res => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "操作成功！"
              });
              this.getList();
            } else {
              this.$message({
                type: "warning",
                message: res.msg
              });
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });          
        });
    },
    linkTo(path,id){
      this.$router.push(path+'?id='+id+'&pageIndex='+JSON.stringify(this.param))
    },
    changeMobile(obj){
      this.couponObj = obj
      this.dialogVisible = true;
    },
    returnName(val){
        let str;
        this.typeArr.map(item=>{
            if(item.value == val){
                str = item.name
            }
        })
        return str
    },
    formatter(row, column, cellValue) {
      return cellValue ? cellValue : "- -";
    },
    addBtn(state){
      state = state||''
       this.$router.push({
         path:'couponEdit',
         query:{
           type:state,
           pageIndex:JSON.stringify(this.param)
         }
       })
    },  
    editBtn(id){
      this.$router.push('couponEdit?id='+id+'&pageIndex='+JSON.stringify(this.param))
    },
    deleteRole:function(id) {
        this.$confirm('确定删除?', '提示', {           
            confirmButtonText: '确定',           
            cancelButtonText: '取消',           
            type: 'warning'         
        }).then(() => {           
            let  url = CONSTANT.URL.LIST.deleteEsCouponByIds;
            let param = [{id:id}] ;
            common.requestAjax(url,JSON.stringify(param),null,(res)=>{
                if(res.status == 200){
                    this.$message({
                        type:'success',
                        message:'删除成功!'
                    });
                    this.getList();
                }
                else{
                    this.$message({
                        type:'warning',
                        message:res.msg
                    })
                }
            })      
        }).catch(() => {           
            this.$message({             
                type: 'info',             
                message: '已取消删除'           
            });                   
        });    
    },
    handSave(formName) {
      let couponObj = this.couponObj
      let obj = {
        "id": couponObj.id,
        "price": this.price,
        "userId": couponObj.userId,
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          let url = CONSTANT.URL.LIST.couponRecharge;
          common.requestAjax(url, JSON.stringify(obj), null, res => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "保存成功！"
              });
              this.getList();
              this.dialogVisible = false;
              this.price = ''
            } else {
              this.$message({
                type: "warning",
                message: res.msg
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handSave1(formName) {
      this.selectVal.forEach(item=>{
        item.validTime = this.user1.validTime
      })
      this.$refs[formName].validate(valid => {
        if (valid) {
          let url = CONSTANT.URL.LIST.changValidDate;
          common.requestAjax(url, JSON.stringify(this.selectVal), null, res => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "保存成功！"
              });
              this.getList();
              this.dialogVisible1 = false;
              this.user1.validTime = ''
            } else {
              this.$message({
                type: "warning",
                message: res.msg
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getList: function() {
        this.dateArr = this.dateArr?this.dateArr:[]
        if(this.dateArr.length){
            this.param.beginDate = this.dateArr[0]
            this.param.endDate = this.dateArr[1]
        }else{
          this.param.beginDate = ''
          this.param.endDate = ''
          this.dateArr=[]
        }
      let url = CONSTANT.URL.LIST.findEsCouponByPage;
      this.loading = true;
      common.requestAjax(url, JSON.stringify(this.param), null, res => {
        this.loading = false;
        let data = res.data;
        this.tableData = data.bussData;
        this.pageCount = data.count;
      });
    },
    search: function(e) {
      if (e.keyCode == 13) {
        this.param.pageIndex = 1;
        this.getList();
      }
    },
    handleSizeChange(val) {
      this.param.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.param.pageIndex = val;
      this.getList();
    }
  }
};
</script>
